package org.lcrystal.tool;

import jakarta.annotation.Resource;
import org.lcrystal.mapper.RecoverMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

@Component
@Configuration
public class Recover implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(Recover.class);

    @Resource(name = "recoverMapper")
    private RecoverMapper recoverMapper;

    @Override
    public void run(String... args) throws Exception {
        if(args.length < 1) {
            System.err.println("");
            System.err.println("**************************************************");
            System.err.println("*    Usage: java -jar recover-db-data.jar path   *");
            System.err.println("*    path: the path of sql files                 *");
            System.err.println("**************************************************");

            System.exit(1);
        }

        int iLine = 0;
        String strLine = null;
        String strFile = null;
        String strPath = args[0];
        BufferedReader br = null;

        try {
            File path = new File(strPath);
            for(String strTemp : path.list()) {
                strFile = strPath + File.separator + strTemp;
                br = new BufferedReader(new FileReader(strFile));

                iLine = 0;
                logger.info("开始从文件：" + strFile + "，恢复数据。");

                while((strLine = br.readLine()) != null) {
                    iLine += recoverMapper.dynamicSql(strLine);
                }

                logger.info("文件：" + strFile + "，恢复完成，共恢复" + iLine + "条数据。");
            }
        } catch (Exception e) {
            String strMessage = "从文件："+ strFile +
                    "，恢复数据报错，第" + (iLine + 1) + "行：\"" +
                    strLine + "\"，报错内容为：" + e.toString();

            logger.error(strMessage);
            System.exit(1);
        } finally {
            if(br != null) {
                br.close();
            }
        }
    }
}
